
//
//  TabOneViewController.m
//  DaJiang
//
//  Created by sally on 16/9/24.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "CellManager.h"
#import "ExpertListViewController.h"
#import "ExpertModel.h"
#import "LevelModel.h"
#import "MainModel.h"
#import "RewardCell.h"
#import "RewardViewController.h"
#import "SearchExpertViewController.h"
#import "SelectCityViewController.h"
#import "TabOneViewController.h"
#import "WebViewController.h"
#import "ThemeCell.h"
#import <SDCycleScrollView/SDCycleScrollView.h>

@interface TabOneViewController () <SDCycleScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIView *cycleView;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UIView *categoryView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) SDCycleScrollView *cycleScrollView; //banner

@property (strong, nonatomic) NSMutableArray *tableData;
@property (strong, nonatomic) UITableView *sbuTable;        //横向table
@property (strong, nonatomic) NSMutableArray *sbuTableData; //横向table数据
@property (strong, nonatomic) NSMutableArray *bannerData;   //banner数据
@property (assign, nonatomic) NSInteger index;              //分类选中项
@property (assign, nonatomic) NSInteger pager;

@end

@implementation TabOneViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setNotification];
  [self initControl];
  [self initData];
  [self loadBannerData];
  [self loadLevel1Data];
  [self setRefresh];
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  
  NSString *locName = [[NSUserDefaults standardUserDefaults] objectForKey:UD_LAST_SELECT_LOC];
  self.addressLabel.text = locName;
  
  //TODO: 列表滑动时，底部有一部分滑不到，估计是隐藏导航栏导致
  
  // 二级页面来到该页面，要动画；tab切换来到该页面，不要动画
  if (self.isFromTab) {
    [self.navigationController setNavigationBarHidden:YES animated:NO];
  } else {
    [self.navigationController setNavigationBarHidden:YES animated:YES];
  }
}

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark 初始化控件
- (void)initControl {
  self.headerView.height = 224;
  [self setSearchView];      //搜索
  [self setCycleScrollView]; //banner
  [self setHorizontalTable]; //分类
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [NSMutableArray array];
  self.sbuTableData = [NSMutableArray array];
  self.bannerData = [NSMutableArray array];
  self.index = 0;
  
  //从plist中获取一级分类列表的缓存数据
  NSMutableArray *arr = [[CacheManager shareInstance] getLastLevelArr];
  self.sbuTableData = [[NSMutableArray alloc] initWithArray:arr];
  [self.sbuTable reloadData];
}

- (void)setNotification {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadRefreshData) name:NoticeRefreshTabOneVc object:nil];
}

#pragma mark 加载banner数据
- (void)loadBannerData {
  [BannerModel queryBannerListWithCompletion:^(NSMutableArray *bannerList) {
    if (bannerList) {
      [self.bannerData removeAllObjects];
      [self.bannerData addObjectsFromArray:bannerList];

      NSMutableArray *imagesURLArr = [NSMutableArray array];
      for (BannerModel *bannerModel in bannerList) {
        NSString *bannerPic = bannerModel.data.banner_pic;
        if (bannerPic) {
          [imagesURLArr addObject:bannerPic];
        }else{
          [self.bannerData removeObject:bannerModel];
        }
      }
      self.cycleScrollView.imageURLStringsGroup = imagesURLArr;
    } else {
      NSError *error = [BannerModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
  }];
}

#pragma mark 加载一级分类数据
- (void)loadLevel1Data {
  [LevelModel queryLevel1ListWithCompletion:^(NSMutableArray *levelList) {
    if (levelList) {
      [[CacheManager shareInstance] cacheLastLevelArr:levelList];
      [self.sbuTableData removeAllObjects];
      [self.sbuTableData addObjectsFromArray:levelList];
      [self.sbuTable reloadData];
    } else {
      NSError *error = [LevelModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
  }];
}

- (void)setRefresh {
  __weak typeof(self) weakSelf = self;
  // 添加下拉刷新列表数据功能
  _tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:weakSelf refreshingAction:@selector(loadRefreshData)];
  _tableView.header.height = 110;//使刷新条完全隐藏，不遮挡状态栏
  
  // 添加上拉加载更多列表数据功能
  _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:weakSelf refreshingAction:@selector(loadMoreData)];
  
  // 触发刷新
  [self loadRefreshData];
}

#pragma mark - 获取数据
- (void)loadRefreshData {
  _pager = 1;
  [self loadData];
}

- (void)loadMoreData {
  _pager = _pager + 1;
  [self loadData];
}

- (void)loadData {
  self.tableView.footer.hidden = NO;
  NSInteger cursor = _pager > 1 ? [[self.tableData lastObject] recommendid] : GCursorInit;
  UIWindow *window = [UIApplication sharedApplication].keyWindow;
  if (_pager == 1) {
    [[CommonMethod sharedCommonMethod] createProgressHUDInView:window withMessage:@""];
  }
  
  NSString *locName = [[NSUserDefaults standardUserDefaults] objectForKey:UD_LAST_SELECT_LOC];
  [RecommendModel queryRecommendListWithLocation:locName cursor:cursor completion:^(NSMutableArray *bannerList) {
    if (bannerList) {
      // 下拉刷新数据
      if (_pager == 1) {
        [self.tableData removeAllObjects];
        [self.tableData addObjectsFromArray:bannerList];
        [self.tableView reloadData];
        
        if (bannerList.count < GListCount) {
          self.tableView.footer.hidden = YES;
        }
      }
      // 上拉加载更多
      else {
        [self.tableData addObjectsFromArray:bannerList];
        [self.tableView reloadData];
        if (bannerList.count < GListCount) {
          self.tableView.footer.hidden = YES;
        }
      }
      
    } else {
      NSError *error = [RecommendModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    
    [MBProgressHUD hideAllHUDsForView:window animated:YES];
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
  }];
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  if (tableView == self.tableView) { //话题+悬赏
    return self.tableData.count + 1;
  } else { //分类
    return self.sbuTableData.count + 1;
  }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (tableView == self.tableView) { //话题+悬赏
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
  } else { //分类
    return SbuTableCellHeight;
  }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (tableView == self.tableView) { //话题+悬赏
    
    //TODO: 两种cell布局时，图片等比问题（适配不同机型）
    
    if (indexPath.row == 1 || (self.tableData.count == 0 && indexPath.row == 0)) { //悬赏
      RewardCell *cell = (RewardCell *) [tableView dequeueReusableCellWithIdentifier:@"RewardCell"];
      if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"RewardCell" owner:nil options:nil] lastObject];
      }
      return cell;
    } else {
      ThemeCell *cell = (ThemeCell *) [tableView dequeueReusableCellWithIdentifier:@"ThemeCell"];
      if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ThemeCell" owner:nil options:nil] lastObject];
      }
      
      NSInteger index = indexPath.row > 1 ? indexPath.row - 1 : 0;
      cell.cellData = [self.tableData objectAtIndex:index];
      return cell;
    }
    
  } else { //分类
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      cell.selectionStyle = UITableViewCellSelectionStyleGray;
      cell.textLabel.textAlignment = NSTextAlignmentCenter;
      cell.textLabel.transform = CGAffineTransformMakeRotation(M_PI / 2);
      [CellManager configCellText:cell type:TextColorType_Black];
    }
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake((SbuTableHeight - SbuTableLineHeight) / 2, SbuTableCellHeight - 1, SbuTableLineHeight, LineHeight)];
    line.backgroundColor = GGrayColor;
    [cell addSubview:line];
    
    if (indexPath.row == 0) {
      cell.textLabel.text = @"全部";
    } else {
      LevelModel *levelModel = [self.sbuTableData objectAtIndex:(indexPath.row - 1)];
      cell.textLabel.text = levelModel.data.user_pro_topic_index;
    }
    
    return cell;
  }
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失
  if (![OperationManager gotoLogin]) {
    return;
  }
  
  if (tableView == self.tableView) { //话题+悬赏
    if (indexPath.row == 1 || (self.tableData.count == 0 && indexPath.row == 0)) { //悬赏
      RewardViewController *vc = [[RewardViewController alloc] init];
      vc.hidesBottomBarWhenPushed = YES;
      [self.navigationController pushViewController:vc animated:YES];
    } else {
      NSInteger index = indexPath.row > 1 ? indexPath.row - 1 : 0;
      RecommendModel *recommendModel = [self.tableData objectAtIndex:index];
      [OperationManager gotoExpertDetailVcWithId:recommendModel.pro_user_data.uid expertName:recommendModel.pro_user_data.user_data.user_name];
    }
    
  } else { //分类
    ExpertListViewController *vc = [[ExpertListViewController alloc] init];
    if (indexPath.row != 0) {
      LevelModel *levelModel = [self.sbuTableData objectAtIndex:(indexPath.row - 1)];
      vc.levelModel = levelModel;
    }
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  }
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
  if (![OperationManager gotoLogin]) {
    return;
  }
  
  BannerModel *bannerModel = [self.bannerData objectAtIndex:index];
  if (bannerModel.data.jump_url && bannerModel.data.jump_url.length > 0) {
    WebViewController *vc = [[WebViewController alloc]init];
    vc.url = bannerModel.data.jump_url;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  }else if (bannerModel.data.pro_uid){
    [OperationManager gotoExpertDetailVcWithId:bannerModel.data.pro_uid expertName:@""];
  }
}

#pragma mark - 私有方法
#pragma mark - 设置搜索控件
- (void)setSearchView {
  self.searchView.layer.cornerRadius = GDefaultCornerRadius;
  self.searchView.layer.masksToBounds = YES;
  UITapGestureRecognizer *addressTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoAddressVc:)];
  [self.addressView addGestureRecognizer:addressTap];
  UITapGestureRecognizer *searchTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoSearchVc:)];
  [self.searchView addGestureRecognizer:searchTap];
}

#pragma mark 跳转地址页
- (void)gotoAddressVc:(UIGestureRecognizer *)tap {
  SelectCityViewController *vc = [[SelectCityViewController alloc] init];
  vc.hidesBottomBarWhenPushed = YES;
  [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 跳转搜索页
- (void)gotoSearchVc:(UIGestureRecognizer *)tap {
  if (![OperationManager gotoLogin]) {
    return;
  }

  SearchExpertViewController *vc = [[SearchExpertViewController alloc] init];
  vc.hidesBottomBarWhenPushed = YES;
  [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 设置滚动图片
- (void)setCycleScrollView {
  self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, ScreenWidth, GExpertImageHeight) delegate:self placeholderImage:[UIImage imageNamed:@"banner_default"]];
  NSArray *imagesURLArr = @[ @"banner_default" ];
  self.cycleScrollView.currentPageDotImage = [UIImage imageNamed:@"PageControlSelectDot"];
  self.cycleScrollView.pageDotImage = [UIImage imageNamed:@"PageControlDot"];
  self.cycleScrollView.localizationImageNamesGroup = imagesURLArr;
  [self.cycleView addSubview:self.cycleScrollView];
}

#pragma mark - 设置横向tableview(分类)
- (void)setHorizontalTable {
  _sbuTable = [[UITableView alloc] init];
  _sbuTable.separatorStyle = NO;
  _sbuTable.transform = CGAffineTransformMakeRotation(M_PI / -2);
  _sbuTable.showsVerticalScrollIndicator = NO;
  _sbuTable.rowHeight = SbuTableCellHeight;
  _sbuTable.delegate = self;
  _sbuTable.dataSource = self;
  _sbuTable.frame = CGRectMake(0, 0, ScreenWidth, SbuTableHeight);
  _sbuTable.width = ScreenWidth;
  [self.categoryView addSubview:_sbuTable];
}

@end
